<?php
/**
 * Created by PhpStorm.
 * User: liu
 * Date: 2016/4/30
 * Time: 9:19
 */

namespace Home\Controller;
use Think\Controller;
use Think\Page;

class UserController extends Controller
{

    function __construct()
    {
        parent::__construct();
        $this->check_user_auth(); //检查权限

        $sh_class = M("shclass");
        $sh_class_array = $sh_class->where(array('id'=>$_SESSION['class']))->select();
        $sh_grade = M("grade");
        $sh_grade_array = $sh_grade->where(array('id'=>$_SESSION['grade'],"in_school"=>0)) ->order("id DESC")->select();

        $this->assign('sh_class_array', $sh_class_array);
        $this->assign('sh_grade_array', $sh_grade_array);

    }

    public function showAll()
    {
        $stu_model = M('stu');
        //导入分页助手类
        import('Org.Util.Page');
        $_REQUEST['poor'] = $_REQUEST['poor'] ? $_REQUEST['poor'] : -1;
        $_REQUEST['term'] = $_REQUEST['term'] ? $_REQUEST['term'] : -1;
        $_REQUEST['grade'] = $_REQUEST['grade'] ? $_REQUEST['grade'] : -1;
        $_REQUEST['class'] = $_REQUEST['class'] ? $_REQUEST['class'] : -1;
        $action = $_REQUEST['action'];
        $map['grade'] = $_SESSION['grade'];
        $map['class'] = $_SESSION['class'];
        if ($_REQUEST['poor'] != -1) {
            $map['poor'] = $_REQUEST['poor'];
        }
        if ($_REQUEST['grade']!= -1) {
            $map['grade'] = $_REQUEST['grade'];
        }
        if ($_REQUEST['class']!= -1) {
            $map['class'] = $_REQUEST['class'];
        }
        //$map['term'] = $current_term;

        if(date("m")>'01' && date('m')<'09' ){
            $current_term = date("Y") . "春";
        }elseif(date("m")=='01'){
            $current_term = (date("Y")-1) . "秋";
        }else{
            $current_term = date("Y") . "秋";
        }

       // echo $current_term;

        $kw = $_REQUEST['kw'];
        $where['t.name'] = array('like', "%{$kw}%");
        $where['t.ID_number'] = array('like', "%{$kw}%");
        $where['t.XJ_number'] = array('like', "%{$kw}%");
        $where['t.mother_tel'] = array('like', "%{$kw}%");
        $where['t.father_tel'] = array('like', "%{$kw}%");
        $where['_logic'] = 'or';
        $map['_complex'] = $where;


        $total = $stu_model
            ->alias('t')
            ->field('t.*,c.name as classname,g.name as gradename')
            ->join('left join ' . C('DB_PREFIX') . 'shclass as c on c.id = t.class')
            ->join('left join ' . C('DB_PREFIX') . 'grade as g on g.id = t.grade')
            ->where($map)
            ->order("t.id DESC")
            ->count();
        $page = new Page($total, 60);
        $page->setConfig("header", '个用户');
        $pageControl = $page->show();

        if ($_REQUEST['term']!= -1) {
            $map['term'] = $_REQUEST['term'];
        }

        if($_REQUEST['term']== '2'){
            $map['term'] = array('exp','is null');
        }

        $stus = $stu_model
            ->alias('t')
            ->field('t.*,c.name as classname,g.name as gradename,s.otime,s.term')
            ->join('left join ' . C('DB_PREFIX') . 'shclass as c on c.id = t.class')
            ->join('left join ' . C('DB_PREFIX') . 'grade as g on g.id = t.grade')
            ->join('left join ' . C('DB_PREFIX') . 'stu_sign as s on t.id = s.stu_id and s.term="'.$current_term.'"')
            ->where($map)
            ->order("t.id DESC")
            ->limit($page->firstRow,$page->listRows)
            ->select();
         //echo $stu_model->_sql();
        // die();
        $tongji = array();
        foreach ($stus as $k=>$v){
            $v['ids'] = $k+1;
            if(!$v['father_name']){
                $v['father_name'] = $v['mother_name'];
            }
            if(!$v['father_tel']){
                $v['father_tel'] = $v['mother_tel'];
            }
            if($v['term']){
                $tongji['had'] += 1;
            }else{
                $tongji['none'] += 1;
            }
            $stus[$k] = $v;
        }

        $this->assign('stus', $stus);
        if ($action == "excel") {

            $fields=array(
                't.name',
                't.sex',
                't.ID_number',
                't.XJ_number',
                'g.name as gradename',
                'c.name as classname',
                't.jiguan',
                't.town',
                't.address' ,
                't.father_name',
                't.father_ID_number',
                't.father_tel',
                't.mother_name',
                't.mother_ID_number',
                't.mother_tel',
                't.poor'
            );

            $stus = $stu_model
                ->alias('t')
                ->field(implode(",",$fields))
                ->join('left join ' . C('DB_PREFIX') . 'shclass as c on c.id = t.class')
                ->join('left join ' . C('DB_PREFIX') . 'grade as g on g.id = t.grade')
                ->where($map)
                ->order("t.id DESC")
                ->select();
            //  echo $stu_model->_sql();
            $excel=array(
                't.name' => '姓名',
                't.sex' => '性别',
                't.ID_number' => '身份证号',
                't.XJ_number' => '学籍号',
                'g.name as gradename' => '年级',
                'c.name as classname' => '班级',
                't.jiguan' => '籍贯',
                't.town' => '乡镇',
                't.address' => '住址',
                't.father_name' => '父亲姓名',
                't.father_ID_number' => '父亲身份证号',
                't.father_tel' => '父亲联系电话',
                't.mother_name' => '母亲家长姓名',
                't.mother_ID_number' => '母亲身份证号',
                't.mother_tel' => '母亲联系电话',
                't.poor' => '是否贫困户'
            );
            $excel_colspan=array("B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q");


            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5", '', '.php');
            import("Org.Util.PHPExcel.IOFactory", '', '.php');

            $objPHPExcel = new \PHPExcel();


// Set document properties
            $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                ->setLastModifiedBy("Maarten Balliauw")
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");

            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '序号');
            foreach($fields as $kf=>$vf){
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($excel_colspan[$kf] . '1', $excel[$vf]);
            }

            foreach ($stus as $k => $v) {

//处理数据完成
                $num = $k + 2;
                $objPHPExcel->setActiveSheetIndex(0)
                    //Excel的第A列，uid是你查出数组的键值，下面以此类推
                    ->setCellValue('A' . $num, $num-1);
                foreach($fields as $kf=>$vf){
                    if(strstr($vf, 'number')){
                        $fgs = '  ';
                    }else{
                        $fgs = "";
                    }
                    $v=array_values($v);
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($excel_colspan[$kf] . $num, $fgs.$v[$kf]);
                }
            }

            $objPHPExcel->getActiveSheet()->setTitle('班级');
            $objPHPExcel->setActiveSheetIndex(0);
            $filename = '班级' . date('YmdHis');
            ob_end_clean();//清除缓冲区,避免乱码
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            //   $objWriter = \PHPExcel_IOFactory::createReader('Excel5');
            //  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;

        }



        $this->assign('count', $total);
        $this->assign('current_term', $current_term);
        $this->assign('tongji', $tongji);
        $this->assign('page_title', "学生列表");
        $this->assign('pageControl', $pageControl);
        $this->display();

    }
    public function showAdd()
    {
        $this->assign('user_list', array('poor'=>0));
        $this->display('update');

    }


    //实现学生修改功能
    public function update()
    {
        header("Content-Type:text/html;charset=utf-8");
        $stu = M('stu');
        $id = $_GET['id'];
        if (!$_POST['name']) {
            $this->error('姓名不能为空！！');
        }

        $IDCard = $_POST['ID_number'];
        $tyear = intval(substr($IDCard, 6, 4));
        $tmonth = intval(substr($IDCard, 10, 2));
        $tday = intval(substr($IDCard, 12, 2));
        $_POST['birthday'] = $tyear . '-' . $tmonth . '-' . $tday;
        if($_POST['action']=='baoming'){

            if(date("m")>'01' && date('m')<'09' ){
                $current_term = date("Y") . "春";
            }elseif(date("m")=='01'){
                $current_term = (date("Y")-1) . "秋";
            }else{
                $current_term = date("Y") . "秋";
            }

            $baoming_array=array(
                'stu_id' => $id,
                'log' => $_POST['name'] . "于".date("Y-m-d H:i:s")."报名成功，班主任：" . $_SESSION['username'],
                'otime' => time(),
                'term' => $current_term,
                'memo'=>$_POST['memo']
            );

            $stu_log = M('stu_sign');
            $check = $stu_log->where(array('stu_id' => $id, 'term' => $current_term))->find();
            if($check){
                $this->error('已经报名了，请勿重复提交！！！');
            }

            $result = $stu_log->add($baoming_array);
            unset($_POST['memo']);
            unset($_POST['action']);
        }
        if ($id) {
            // $birth = strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8);
            // $sex = substr($idcard, (strlen($idcard)==15 ? -2 : -1), 1) % 2 ? '男' : '女';

            $stu_list = $stu->where("id=".$id)->save($_POST);
            if ($stu_list) {
                $this->success('成功！！');
                $this->redirect('showAll');
            } else {
                $this->error('失败！！');
            }
        } else {
            $result = $stu->add($_POST);
            if ($result) {
                $this->success('成功！！');
                $this->redirect('showAll');
            } else {
                $this->error('失败！！');
            }
        }
        $this->redirect('showAll');//重定向到控制器的方法  display是本控制的方法

    }

    public function showUpdate()
    {

        $stu = M('stu');
        $id = $_GET['id'];
        $stu_list = $stu->where("id=$id")->find();
        $this->assign('page_title', "修改");
        $this->assign('user_list', $stu_list);
        $this->display('update');
    }
    public function baoming()
    {

        $stu = M('stu');
        $id = $_GET['id'];
        $stu_list = $stu->where("id=$id")->find();
        $this->assign('page_title', "报名");
        $this->assign('user_list', $stu_list);
        $this->display('update');
    }

    /**
     * 批量报名
     */
    public function batch_baoming()
    {
        if(date("m")>'01' && date('m')<'09' ){
            $current_term = date("Y") . "春";
        }elseif(date("m")=='01'){
            $current_term = (date("Y")-1) . "秋";
        }else{
            $current_term = date("Y") . "秋";
        }
        foreach ($_POST['id'] as $v){
        $baoming_array[]=array(
            'stu_id' => $v,
            'log' => "批量报名 ：".date("Y-m-d H:i:s")."报名成功，班主任：" . $_SESSION['username'],
            'otime' => time(),
            'term' => $current_term,
            'memo'=>'批量报名'
        );
        }
        $stu_log = M('stu_sign');
        $result = $stu_log->addAll($baoming_array);
        if ($result) {
                $this->success('批量报名成功！！');
                $this->redirect('showAll');
        } else {
            $this->error('批量报名失败！！');
            $this->redirect('showAll');
        }
    }

    //实现学生删除功能

    //实现学生删除功能
    public function del_close()
    {


        $stu=M('stu');
        $id=$_GET['id'];
            $result= $stu->where(array("id"=>$id,"grade"=>$_SESSION['grade']))->delete();
            if($result) {
                $this->success('学生删除成功！');
            }else{
                $this->error('学生删除失败！');
            }

  }
//用户注册方法显示
    public function showReg()
    {
       $this->display('reg');
    }
    //验证码方法
    public function verify()
    {//加载图形类
        $config =    array(
            'imageH'    =>50,               // 验证码图片高度
            'imageW'    =>120,               // 验证码图片宽度
            'fontSize'    => 18,    // 验证码字体大小
            'length'      =>  4,     // 验证码位数
            'useNoise'    =>    false, // 关闭验证码杂点
        );
        $Verify = new \Think\Verify( $config);
        $Verify->entry();
    }
    public function reg()
    {
    if($_POST['reg'])
    {
     $verify = new \Think\Verify();
     $verify_result=$verify->check($_POST['verify'], '');
     if(!$verify_result){
         $this->error('验证码错误！');
     }
     if($_POST['password']!=$_POST['passwordq'])
     {
         $this->error('两次输入的密码不一致！');
     }
     else  {
           $user=M('user');
         if($_POST['role']==1){//班级老师
             $stuinfo['username']=$_POST['username'];
             $stuinfo['password']=md5($_POST['password']);
             $stuinfo['role']=$_POST['role'];
             $stuinfo['grade']=$_POST['grade'];
             $stuinfo['class']=$_POST['class'];
         }
         if($_POST['role']!=1) { //年级主任
             $stuinfo['username']=$_POST['username'];
             $stuinfo['password']=md5($_POST['password']);
             $stuinfo['role']=$_POST['role'];
             $stuinfo['grade']=$_POST['grade'];
             $stuinfo['class']=0;
         }
         $user->add($stuinfo);
         $this->success('数据添加成功');

     }
 }

 }

//用户登录页面的展示
    public function showLogin()
    {

        $this->redirect('index/index'); //redirect下面跟控制器
    }
    //用户登录页面方法展示


    //修改密码
    function showPwdUpdate()
    {   $this->assign('username',  $_SESSION['username']);
        $this->display('PwdUpdate');
    }
    function PwdUpdate()
    {
        header("Content-Type:text/html;charset=utf-8");
        $user=M('user');
        $username=$_SESSION['username'];
        $userinfo=$user->where("username='$username'")->find();

        //判断原密码是否输入正确
     if($userinfo['password']!=md5($_POST['password']))
     {
         $this->error('原密码输入错误！！');
      $this->redirect('showPwdUpdate');
     }
     if($_POST['passwordNew']!=$_POST['passwordNewq']){
           $this->error('两次新密码输入不一致！！');
         $this->redirect('showPwdUpdate');
     }
    else{
       $userinfo2['password']=md5($_POST['passwordNew']);
       $result= $user->where("username='$username'")->save($userinfo2);

            if($result){
             //   $this->success('修改成功！！');
            //$this->redirect('showAll');
            }else{
                $this->error('修改失败！！');
                $this->redirect('showPwdUpdate');

            }
        $this->redirect('showAll');
    }
    }


}